package ee.greaton.kultuuriaken;

import java.util.LinkedHashMap;
import java.util.Map;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;

public class SectionedListAdapter extends BaseAdapter {
	public final Map<String, Adapter> adapters = new LinkedHashMap<String, Adapter>();
	public final ArrayAdapter<String> headers;
	public final static int HEADER_TYPE = 0;

	public SectionedListAdapter(Context context) {
		if(Config.theme == 0){
			headers = new ArrayAdapter<String>(context, R.layout.tume_header,
				R.id.list_header);
		}else{
			headers = new ArrayAdapter<String>(context, R.layout.hele_header,
					R.id.list_header);
		}
	}

	public void addSection(String title, Adapter adapter) {
		this.headers.add(title);
		this.adapters.put(title, adapter);
	}

	public Object getItem(int position) {
		for (Object section : this.adapters.keySet()) {
			Adapter adapter = adapters.get(section);
			int size = adapter.getCount() + 1;
			if (position == 0) {
				return section;
			}
			if (position < size) {
				return adapter.getItem(position - 1);
			}
			position -= size;
		}
		return null;
	}

	public int getCount() {
		int total = 0;
		for (Adapter adapter : this.adapters.values()) {
			total += adapter.getCount() + 1;
		}
		return total;
	}

	public boolean areAllItemsSelectable() {
		return false;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		int sectionnum = 0;
		for (Object section : this.adapters.keySet()) {
			Adapter adapter = adapters.get(section);
			int size = adapter.getCount() + 1;
			if (position == 0) {
				return headers.getView(sectionnum, convertView, parent);
			}
			if (position < size) {
				return adapter.getView(position - 1, convertView, parent);
			}
			position -= size;
			sectionnum++;
		}
		return null;
	}

	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getViewTypeCount() {
		int total = 1;
		for (Adapter adapter : this.adapters.values()) {
			total += adapter.getViewTypeCount();
		}
		return total;
	}

	@Override
	public int getItemViewType(int position) {
		int type = 1;
		for (Object section : this.adapters.keySet()) {
			Adapter adapter = adapters.get(section);
			int size = adapter.getCount() + 1;
			if (position == 0) {
				return HEADER_TYPE;
			}
			if (position < size) {
				return type + adapter.getItemViewType(position - 1);
			}
			position -= size;
			type += adapter.getViewTypeCount();
		}
		return -1;
	}

	@Override
	public boolean isEnabled(int position) {
		return (getItemViewType(position) != HEADER_TYPE);
	}
}
